package com.cly.common.config;


import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@ConditionalOnClass(org.springframework.boot.SpringApplication.class)
public class ThreadPoolTaskExecutorSchedulerConfig {

    /**
     * 配置ThreadPoolTaskExecutor, 用于执行异步任务的调度
     * @return
     */
    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolExecutorConfig() {
        // 创建线程池对象
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        // 设置线程池核心线程数
        threadPoolTaskExecutor.setCorePoolSize(3);
        // 设置最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(5);
        // 设置队列容量
        threadPoolTaskExecutor.setQueueCapacity(10);
        // 设置线程空闲时间
        threadPoolTaskExecutor.setKeepAliveSeconds(60);
        // 设置拒绝策略
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化线程池并返回
//        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }

    /**
     * 配置ThreadPoolTaskScheduler, 用于执行定时任务
     * @return
     */
    @Bean(name = "threadPoolTaskScheduler")
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.setPoolSize(5); // 设置线程池大小
        return threadPoolTaskScheduler;
    }

}
